﻿<?php
/**  
* Dbmgr.php
* 
*/

define ('DB_HOST',		'localhost');
define ('DB_NAME', 		'oop');
define ('DB_USER', 		'root');
define ('DB_PASSWORD', 	'apmsetup');  
define ('DB_CHARSET',   'utf8');

require_once(CLASS_PATH."/__autoload.php");

class Dbmgr extends Datamgr
{
   protected $host, $dbname, $user, $password, $connection, $close_flag;

   public function __construct($connection, $close_flag)
   {
      parent::__construct();	  
      $this->connection = $connection;
      $this->close_flag = $close_flag;
   }

   protected function db_open()
   {
      if (empty($this->connection))
      {
	     $this->db_access();
         $this->connection = @mysqli_connect($this->host, $this->user, $this->password);

         if (!$this->connection)
         {
            $this->db_handle_error('DB 연결 오류');
            return false;
         }

         if (!mysqli_select_db($this->connection, $this->dbname))
         {
            $this->db_handle_error('DB 선택 오류');
            return false;
         } 
      }
	  
/*////////////////////////	  
	      $msg = ($this->connection) ? "<b>Dbmgr.php >>>  DB Connected </b><br /><br />" : "<b>Dbmgr.php >>>  DB Connect ERROR</b><br /><br />";
		  echo $msg;
/**/////////////////////////	   
 
      return true;
   }
   
   protected function db_access()
   {
	  $this->host 		= DB_HOST;	 
	  $this->dbname 	= DB_NAME;
	  $this->user 		= DB_USER;
	  $this->password 	= DB_PASSWORD;
   }

   public function db_close()
   {
      if ($this->connection)
         mysqli_close($this->connection);
   }

   public function db_query($query, $char = DB_CHARSET)     
   {
      mysqli_query($this->connection, "set names ".$char);  // 종종 한글이 깨짐 
	  return mysqli_query($this->connection, $query);    
   }

   public function db_numrows($result)     
   {
      return mysqli_num_rows($result);
   }
   
//********** DB 핸들링

    // PHP-HTC모듈레퍼런스 크라운 출판사 p.312
	protected function db_select($table, $where="", $fields="*", $order='')
	{
	 	$qry = (isset($order)) ? " ORDER BY $order" : null;
		$qry = "SELECT $fields FROM $table WHERE $where".$qry; 

/*////////////////////////	  
	     echo "<b>DBmgr.php >>> db_select() \$qry : </b> ".$qry."<br /><br />";
/**///////////////////////	  

		return $this->db_query($qry);
	}


	public function db_insert($table, $arr)   // $arr 연관배열
	{
		$keys = array_keys($arr);
		$fieldName = implode(', ', $keys); 
		
		array_walk($arr, "set_quotation");		
		$fieldData = implode(', ', $arr);
		
		$qry = "INSERT INTO $table ($fieldName) VALUES ($fieldData)";

/*////////////////////////	  
	     echo "<b>DBmgr.php >>> db_insert() \$qry : </b> ".$qry."<br /><br />";
/**///////////////////////	  

		return $qry;  //  $this->db_query($qry);
		
	}

	public function db_insert_multi($table, $fields, $arr)  // $arr 연관배열
	{
		$len  = count($arr);
		$data = array();
		
		while($len--)
		{
			array_walk($arr[$len], "set_quotation");			
			$data[] = "(".implode(',', $arr[$len]).")"; 	
		//  $data[] = "( {implode(',', $arr[$len])} )"; 	
		}
		
	//	$qry .= implode(', ', $data);
		$qry  = "INSERT INTO $table ($fieldName) VALUES ".implode(', ', $data);
		
/*////////////////////////	  
	     echo "<b>DBmgr.php >>> db_insert_multi() \$qry : </b> ".$qry."<br /><br />";
/**///////////////////////	  
		
		return $qry;  //  $this->db_query($qry);
	}

	public function db_update($table, $arr, $where="")   // $arr 연관배열
	{
		$data = array();
		array_walk($arr, "set_quotation");		
		
		while(list($key, $val) = each($arr))
		{
			$data[] = "$key = $val";	
		}
		
		$qry  = "UPDATE $table SET ".implode(', ', $data)." WHERE $where";		
		
/*////////////////////////	  
	     echo "<b>DBmgr.php >>> db_update() \$qry : </b> ".$qry."<br /><br />";
/**///////////////////////	  
		
		return $qry;  //  $this->db_query($qry);
	}

	public function db_delete($table, $where='')
	{
		
		$qry = "DELETE FROM $table WHERE $where";
		
/*////////////////////////	  
	     echo "<b>DBmgr.php >>> db_delete() \$qry : </b> ".$qry."<br /><br />";
/**///////////////////////	  
		
		return $qry;  //  $this->db_query($qry);
	}


   protected function set_quotation(&$val, $key)
	{
		$val = "'".$val."'";	
	}

   protected function get_insert_id()
   {
	  return mysqli_insert_id($this->connection);
   }

   protected function db_handle_error($str)
   {
       echo "알림: ".$str;
	   return false;
   }



//********** 유틸
   public function cleanKeyword($str, $split_word)     
   {
      $str     = explode($split_word, $str);
      $pattern = "/[^A-Za-z0-9]/";
	  $keywords = array();
	  
      foreach($str as $word){
		$word       = trim($word);
		$word       = strip_tags($word);
		$word       = preg_replace($pattern, "", $word);
	    if($word === '')  continue;      	// 공백제거
		$word       = strtolower($word);
	//	$word       = self::cleanHex($word);      // todo: x나 X로 시작하는 문자는 글자수 체크 하여 16진수 판별 필요
		$word       = substr($word, 0, 12);      // 연속 최대글자 제한
	    $keywords[] = mysqli_real_escape_string($this->connection, $word);
      }	
	  return $keywords;
   }     


   public function cleanWord($input, $max=null) 
   {   
      $input = trim($input);
      $input = strip_tags($input);      // cf. htmlentities() 
	  $input = self::cleanHex($input);  

	  if(isset($max) && $max > 1)  $input = substr($input, 0, $max);      // 연속 최대글자 제한
	  if(get_magiquotes_gpc())   $input = stripslashes($input);         // 이중 escape 방지용
	  $input = mysqli_real_escape_string($this->connection, $input);
	  return $input;
   }
   

   public function cleanHex($input)     // 16진수 buffer overflow 처리용
   {
      $clean = preg_replace("![\][xX]([A-Fa-f0-9]{0,3})!", "", $input);
	  return $clean;
   }

}
?>

<?php
/** 폼에서 넘어온 $name 처리,   cleanWord() 필요함
$name = isset($_POST["name"]) ? $_POST["name"] :'';
$name_pattern = "/[^A-Za-z0-9.]/";   
$name = strtolower(preg_replace($name_pattern, "", $name));
*/
?>